﻿--[[
   @brief    control module for repair game
   @author   farleywen
   @version  1.0
   @date     2015-12-18
--]]

repair_game_control =
{
    last_game_id_sel_ = 0;  -- 最后一个呼叫选择窗口的游戏id
    init = function()
        base_utility.log("[repair_game_control] init");
        ierd_tgp.tpf_ui.Require("tool_box\\repair\\model.lua")
        ierd_tgp.tpf_ui.Require("tool_box\\repair_game\\model.lua")
        ierd_tgp.tpf_ui.Require("tool_box\\repair_game\\view.lua");
    end;

    open_repair_game_page = function(event_ids, json)
        local param = base_utility.json_to_table(json);
        repair_game_view.show(param.id);
    end;

    -- 增加服务接口：打开修复窗口(统一)
    on_service_unified_repair_game = function(data)
        base_utility.log("[repair_game]on_service_unified_repair_game, " ..
                base_utility.table_to_json(data));
        if data == nil or data.game_id == nil then
            base_utility.log("open_repair_game_wnd: param data is nil");
            return;
        end
        local game_id = data.game_id;
        local param = {param = game_id};
        if game_id == GAME_ID.GAME_ID_LOL then
            local query_param = {
                game_id = game_id;
                action = repo_sync_action.kActionRepair;
            };
            local query_cfg = comm_center.call_service("Svr_GetRepoActionSwitch", query_param);
            if nil ~= query_cfg and true == query_cfg.is_open then
                param.id = game_id;
                event_center.send_event(tool_box_event.OPEN_REPAIR_GAME_PAGE, base_utility.table_to_json(param));
            else
                event_center.send_event(tool_box_event.OPEN_LOL_REPAIR_PAGE, base_utility.table_to_json(param));
            end
        elseif game_id == GAME_ID.GAME_ID_CF then
            event_center.send_event(tool_box_event.OPEN_CF_REPAIR_PAGE, base_utility.table_to_json(param));
        elseif game_id == GAME_ID.GAME_ID_DNF then
            event_center.send_event(tool_box_event.OPEN_DNF_REPAIR_PAGE, base_utility.table_to_json(param));
        else
            param.id = game_id;
            event_center.send_event(tool_box_event.OPEN_REPAIR_GAME_PAGE, base_utility.table_to_json(param));
        end
    end;

    -- 增加服务接口：打开修复窗口
    open_repair_game_wnd = function(data)
        if data == nil or data.game_id == nil then
            base_utility.log("open_repair_game_wnd: param data is nil");
            return;
        end
        if tonumber(data.game_id) == GAME_ID.GAME_ID_TGP then
            repair_game_control.req_repo_repair_cfg();
        end;
        if false == repair_game_control.check_can_start(data) then
            repair_game_control.show_warning_dlg();
            return;
        end;
        repair_game_view.show(data.game_id);
    end;

    check_can_start = function(data)
        if tonumber(data.game_id) ~= GAME_ID.GAME_ID_TGP then
            return true;
        end;

        local pre_status = repair_game_model.wg_repair_latest_;
        repair_game_model.wg_repair_latest_ = data.latest;

        local dlg_ptr = repair_game_model.game2dlg_[data.game_id];
        if dlg_ptr == nil then
            return true;
        end;
        
        if pre_status == nil or pre_status == repair_game_model.wg_repair_latest_ then
            return true;
        end;
        repair_game_model.wg_repair_latest_ = pre_status;
        return false;
    end;

    show_warning_dlg = function()
        if repair_game_model.warning_tips_id_ ~= nil then
            poptips_view:new_win_close(ui_utility.uilib(), repair_game_model.warning_tips_id_);
            repair_game_model.warning_tips_id_ = nil;
        end;
        local zParam = 
        {
            position = "center",
            title = LoadStr("REPAIR_WEGAME_TITLE"),
            width = 480,
            height = 230,
            titleIcon = "",
            icon = "",
            tipsIcon = poptips_icons.kWarning,
            descTitle = LoadStr("REPAIR_WEGAME_CONFLICT");
            desc = "";
            parent_id = main_id,
            modal = false,
            always_center = true,
            is_multi_win = true,
            okBtn = 
            {
                visible = "true",
                text = LoadStr("POP_WND_COMMON_OK"),
                close_win = true,
                handle = function()
                end
            },
            cancelBtn = 
            {
                visible = "false",
                text = "";
                handle = function()
                end
            }
       };

       repair_game_model.warning_tips_id_ = poptips_control.show_tips(zParam);
    end;

    get_repair_info = function(data)
        if data == nil or data.game_id == nil or data.latest == nil then
            return data;
        end;

        if data.game_id == GAME_ID.GAME_ID_TGP and
           repair_game_model.wg_repair_latest_ ~= nil and
           repair_game_model.wg_repair_latest_ == true then
            base_utility.log("get_repair_info: wg repair latest");
            data.latest = 1;
            data.stable_version = repair_game_model.repo_stable_version_;
        end;
        return data;
    end;

    -- 增加服务接口：关闭修复窗口
    close_repair_game_wnd = function(data)
        if data == nil or data.game_id == nil then
            base_utility.log("close_repair_game_wnd: param data is nil");
            return;
        end
        repair_game_view.close_by_gameid(data.game_id);
    end;

    get_gamefix_on_progress = function(event_ids, json_str)
        local param = base_utility.json_to_table(json_str);
        local game_id = param.game_id;
        repair_game_control.lua_call_JS("check_progress", json_str, game_id);
        -- 增加取消互斥量的逻辑
        local finish = param.finish;
        if finish == 1 then
            repair_game_control.set_operate_game_state_for_other_wegame(game_id, false);
            repair_game_control.operate_download_mgr_start_or_stop(true);
        end
    end;

    lua_call_JS = function(func_name, json, game_id) 
        ierd_tgp.tpf_ui.Log("repair_game_control lua_call_JS.fuc_name="..func_name);
        local dlg = repair_game_model.game2dlg_[game_id];
        if dlg == nil then
            base_utility.log("[repair_game_control] lua_call_JS dlg is null, gameid= "..game_id);
            return;
        end
        local dlg_id = dlg:GetControlID();
        local uilib = ui_utility.uilib();
        local nQBWebID = MainCommon.get_child_id(uilib, dlg_id, "QBWebBrowser_Repair");
        local pControl = uilib:GetControlPtr(nQBWebID);
        local pQBWeb = tolua.cast(pControl, "Tenio::IQBWebBrowser");
        local const_func_name, str_func_name = U8toCUIStr(func_name);
        local const_json_param, str_json_param = U8toCUIStr(json);
        ierd_tgp.tpf_ui.Log("lua_call_JS start.");
        pQBWeb:ExcecuteJS(const_func_name, const_json_param);
        ierd_tgp.tpf_ui.Log("lua_call_JS success.");
    end;
    
    on_js_callback = function(uilib, fuc_name, json, js_id)
        ierd_tgp.tpf_ui.Log("[repair_game_control] on_js_callback.fuc_name="..fuc_name);

        if fuc_name ~= "check_progress"
        and fuc_name ~= "init_show_config"
        and fuc_name ~= "open_repair_game_page"
        and fuc_name ~= "get_gamefix_on_progress"
        and fuc_name ~= "jc_close_window"
        and fuc_name ~= "OnNavigateOK" then
            ierd_tgp.tpf_ui.Log("[repair_game_control] on_js_callback, invalid, fuc_name="..fuc_name);
            return;
        end
        local game_id = repair_game_model.js2game_[js_id];
        local dlg = repair_game_model.game2dlg_[game_id];
        if dlg == nil then
            base_utility.log("[repair_game_control] on_js_callback dlg is null, js_id= "..js_id);
            return;
        end

        local dlg_id = dlg:GetControlID();
        if fuc_name == "jc_close_window" then
            repair_game_view.close_dlg(uilib, dlg_id, 0, 0);
            return;
        end
        local nQBWebID = MainCommon.get_child_id(uilib, dlg_id, "QBWebBrowser_Repair");
        local control = uilib:GetControlPtr(nQBWebID);
        local component = tolua.cast(control, "Tenio::IQBWebBrowser");
        local const_func_name, str_func_name = U8toCUIStr(fuc_name);
        local const_ui_str, str_holder = U8toCUIStr(json);
        
        paramTable = base_utility.json_to_table(json);
        repair_game_control[fuc_name](uilib, paramTable, js_id);
    end;
    
    OnNavigateOK = function(uilib, sWebUrl, dwCtrlID)
        base_utility.log("[repair_game_control] OnNavigateOK, url="..tostring(sWebUrl));
        local uilib = ui_utility.uilib();
        local dlg_id =  MainCommon.get_parent_id(uilib, dwCtrlID);
        local loading_id = MainCommon.get_child_id(uilib, dlg_id, "pnlLoading");
        local nQBWebID = MainCommon.get_child_id(uilib, dlg_id, "QBWebBrowser_Repair");
        ui_utility.setproperty_by_id(loading_id,"Visible","false");
        ui_utility.setproperty_by_id(nQBWebID,"Visible","true");
    end;

    OnNavigateFail = function(uilib, sWebUrl, dwCtrlID)
        base_utility.log("[E][repair_game_control] OnNavigateFail, url="..tostring(sWebUrl), true);
        local dlg_id =  MainCommon.get_parent_id(uilib, dwCtrlID);
        local dlg_ctrl = ui_utility.get_ctrl_ptr_by_id(dlg_id);
        --shadow_helper.create_shadow(dlg_id);
        dlg_ctrl:Show(TRUE);
        dlg_ctrl:BringToTop();
    end;

    check_progress = function(uilib, param, js_id)
        local game_id = repair_game_model.js2game_[js_id];
        if game_id == nil then
            return;
        end;
        local data_out = comm_center.call_service("i_service_allow_continue_operation_game",
                            {game_id = game_id});
        if data_out ~= nil and not data_out.bAllowContinue then
            return
        end

        -- 其中action_id，1：Check，2：Fix，3:StopCheck, 4：StopFix
        local fix_toolbox = repair_game_model.get_fix_toolbox();
        if fix_toolbox == nil then
            return;
        end
        local set_mutex = false; 
        if param.action_id == 1 then
            fix_toolbox:Check(game_id);
            set_mutex = true;
            repair_game_control.operate_download_mgr_start_or_stop(false);
        elseif param.action_id == 2 then
            fix_toolbox:Fix(game_id);
            set_mutex = true;
        elseif param.action_id == 3 or param.action_id == 4 then
            fix_toolbox:Stop(game_id);
            set_mutex = false;
            repair_game_control.operate_download_mgr_start_or_stop(true);
        end;

        repair_game_control.set_operate_game_state_for_other_wegame(game_id, set_mutex);
    end;
    
    -- 网页配置信息初始化
    init_show_config = function(uilib, param, js_id)
        base_utility.log("[repair_game_control] init_show_config"..js_id);
        local game_id = repair_game_model.js2game_[js_id];
        local fix_ui_info = ierd_tgp.fix_toolbox.FixUIInfo:new();
        local fix_toolbox = repair_game_model.get_fix_toolbox();
        local response = nil;
        if nil ~= fix_toolbox then
            response = fix_toolbox:GetFixUIInfo(game_id, fix_ui_info);
        end
        if response then
            local item_num = fix_ui_info.item_count;
            
            local dlg = repair_game_model.game2dlg_[game_id]; 
            if dlg == nil then
                base_utility.log("[repair_game_control] on_js_callback dlg is null, js_id= "..js_id);
                return;
            end
            local dlg_id = dlg:GetControlID();
            -- 更改界面高度
            if item_num > repair_game_view.MAX_ITEM_NUM_SHOW then
                ui_utility.setproperty_by_id(dlg_id, 'Height', tostring(repair_game_view.DLG_MAX_LENGTH));
            elseif item_num >= 1 then
                ui_utility.setproperty_by_id(dlg_id, 'Height', tostring(repair_game_view.DLG_FRAME_LENGTH+repair_game_view.ITEM_LENGTH*item_num));
            end
            
            local param = {};
            param.count = item_num;
            param.config = {};        

            for i = 0, item_num-1 do
                local item = fix_ui_info.items[i];
                param.config[i] = {title = (item.title), desc = (item.desc),
                desc_pass = (item.desc_check_pass), desc_broken = (item.desc_check_broken)};
            end

            local json_str = base_utility.table_to_json(param);
            repair_game_control.lua_call_JS("init_show_config", json_str, game_id)
            local pRepairDlg = repair_game_model.game2dlg_[game_id];
            
            if pRepairDlg ~= nil then
                --shadow_helper.create_shadow(dlg_id);
                pRepairDlg:Show(TRUE);
            end
            
        else
            base_utility.log("[repair_game_control] init_show_config null"..game_id);
        end 
        fix_ui_info:delete();
    end;

    set_operate_game_state_for_other_wegame = function(game_id, is_operate)
        local game_lib =
            base_utility.get_component_adapter("IGame_library",
                "ierd_tgp.game_library.Get_game_library_adapter();");
        if game_lib ~= nil then
            game_lib:SetGameOperStateMutex(game_id, is_operate);
        end
     end;

     operate_download_mgr_start_or_stop = function(is_start)
        local param_data = comm_center.call_service("Svr_IsOpenGameDownloadMgr", nil);
        if param_data == nil then
            ierd_tgp.tpf_ui.Log(
                "[GameDownloadMgr][operate_download_mgr_start_or_stop]param_data is nil");
            return;
        end;
        if param_data.is_open == false then
            ierd_tgp.tpf_ui.Log(
                "[GameDownloadMgr][operate_download_mgr_start_or_stop]switch is closed");
            return;
        end;

        if is_start then
            base_utility.log("[GameDownloadMgr]repair stop, start download to game download mgr");
            comm_center.call_service("i_service_gamedl_mgr_start", {game_id = 0});
        else
            base_utility.log("[GameDownloadMgr]repair begin, stop download to game download mgr");
            comm_center.call_service("i_service_gamedl_mgr_pause", {game_id = 0});
        end;
     end;
    
    on_main_wnd_show = function(data)
        if data ~= nil and data.isfirst ~= nil and data.isfirst ~= 0 then
            repair_game_control.req_repo_repair_cfg();
        end;
    end;

    req_repo_repair_cfg = function()
        base_utility.log("[repair_game_control]req_repo_repair_cfg");
        if repair_game_model.is_request_repo_repair_cfg_ == true then
            return;
        end;
        repair_game_model.is_request_repo_repair_cfg_ = true;

        local client_type = 1;
        if base_utility.is_type_of_oversea_ver() then
            client_type = 2;
        end

        local post_data = {
                data_names = "wegame_home_configs",
                command = "list_all",
                params = {
                    start_page = 0,
                    items_per_pager = 50
                },
                stamp = {
                    credential = {
                        agent_client_type = client_type,
                    },
                    agent_client_language = base_utility.get_currrent_language_str();
                }
            };
        base_utility.curl_request_async(LoadStr("GL_GAME_CONFIG_URL")
        , "repair_game_control.on_req_repo_repair_cfg"
        , false, nil, true, nil, base_utility.table_to_json(post_data));
    end;
    
    on_req_repo_repair_cfg = function(rsp)
        repair_game_model.is_request_repo_repair_cfg_ = false;
        base_utility.log("[repair_game_control]on_req_repo_repair_cfg"..rsp);
        local res_tbl = base_utility.json_to_table(rsp);
        if nil == res_tbl or nil == res_tbl.result then
            return;
        end
        if 0 ~= tonumber(res_tbl.result.error_code) then
            return;
        end

        local items_count = 0;
        if nil ~= res_tbl.items and type(res_tbl.items) == "table" then
            for key, item in pairs(res_tbl.items) do
                if item ~= nil and 
                   item.name ~= nil and item.name == repair_game_model.repo_repair_cfg_name and
                   item.value ~= nil and item.value ~= "" then
                    local value_tbl = base_utility.json_to_table(item.value);
                    if value_tbl ~= nil and value_tbl.stable_version ~= nil then
                        repair_game_model.repo_stable_version_ = tostring(value_tbl.stable_version);
                        base_utility.log(
          "[repair_game_control]get stable version:"..repair_game_model.repo_stable_version_, true);
                    end;
                end;
            end
        end
    end;
};

repair_game_control.init();
